package com.eryos.android.cigarettecounter;

/**
 * Project :  CigaretteCounter
 * Author :   Olivier Combe 
 * URL :      http://eryos.fr/CigaretteCounter/
 *
 * Copyright (C) 2011 - Olivier Combe 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

//import android.os.Bundle;
//import android.view.View;

import java.util.Calendar;
import java.util.TimeZone;

import android.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.eryos.android.cigarettecounter.beans.SmokeTime;
import com.eryos.android.cigarettecounter.io.Preferences;
import com.eryos.android.cigarettecounter.widget.CigaretteCounterWidger;

public class CigaretteCounter extends RootActivity {

	/** *************** Static Variables *************** **/	
	private final static String NA_LABEL 	= "NA";
	
    /** *************** Instance Variables *************** **/	
    private float cigarettePrice = 0;
    private int dailyCount = 0;
    private double weekAvg = 0;
    private double monthAvg = 0;
    private SmokeTime last = new SmokeTime();
    //private SmokeTime delay = new SmokeTime();
    private String cigarette 	= "";
    private String day = "";
    private String hour = "";
    private String days = "";
    private String minute = "";
    private String minutes = "";
    private int nbCigarettes = 1;
    
    /** *************** UI Elements *************** **/
    private TextView dailyCountValue;
    private TextView lastCigValue;
    private TextView avgWeekValue;
    private TextView avgMonthValue;
	
    private Button addCigaretteButton; 
    private Button addPastCigaretteButton; 
    private Button showWeeklyStatButton; 
    private Button showMonthlyStatButton; 
    
	private Preferences pref;

	/** *************** *********** *************** **/
    
    /**
     * init Values ( not UI ) for this activiry from DB / Network / etc.
     */
    public void initValues(){
    	/* Retrieve the Cigarette price */
    	pref = new Preferences(getSharedPreferences(PREFS_NAME, 0));
    	pref.readParamFromFile();
    	cigarettePrice = pref.getCigarettePrice();
    	
    	/* Refresh the UI with DB values */
    	retieveDataFromDB();
    }
    /**
    
     * Method used to refresh the Daily Counter  
     */
    public void showDailyCount(){  
    	Log.d(getLogTag(), "showDailyCount");
    	dailyCountValue.setText(dailyCount+" "+cigarette);
    }
    
    /**
     * Method used to refresh the Weekly Average  
     */
    public void showWeeklyAverage(){
    	Log.d(getLogTag(), "showWeeklyAverage");
    	final String weekValueLabel = weekAvg+" "+cigarette+" / "+day;
    	if ( weekAvg <= 0 )
    		avgWeekValue.setText(NA_LABEL);
    	else
    		avgWeekValue.setText(weekValueLabel);
    }
    
    /**
     * Method used to refresh the Monthly Average  
     */
    public void showMonthlyAverage(){
    	Log.d(getLogTag(), "showMonthlyAverage");
    	String monthValueLabel = monthAvg+" "+cigarette+" / "+day;
    	if ( monthAvg <= 0 )
    		avgMonthValue.setText(NA_LABEL);
    	else
    		avgMonthValue.setText(monthValueLabel);
    }
    
    /**
     * Method used to refresh the Delay since Last Cigarette  
     */
    public void showDelaySinceLast(){
    	Log.d(getLogTag(), "showDelaySinceLast");
    	String lastLabel = "" ;
    	Log.d(getLogTag(), "Last Cigarettes : "+last);
    	if ( last.getDay() > 0 ){
    		lastLabel = last.getDay()+" "+days+" "+last.getHour()+" "+hour/*+" "+last.getMinute()+" "+minute+" ("+last.getTotalMinutes()+" "+minutes+")"*/;
    	}else {
	    	if ( last.getHour() == 0 )
	    		lastLabel = last.getMinute()+" "+minute/*+" ("+last.getTotalMinutes()+" "+minutes+")"*/;
	    	else
	    		lastLabel = last.getHour()+" "+hour+" "+last.getMinute()+" "+minute+" ("+last.getTotalMinutes()+" "+minutes+")";
    	}

    	if ( last != null && last.getTotalMinutes() < 0 )
    		lastCigValue.setText(NA_LABEL);
    	else
    		lastCigValue.setText(lastLabel);
    }
    
    /**
     * Method used to refresh the Average delay between 2 cigarettes  
     */
    public void showAverageDelay(){
    	Log.d(getLogTag(), "showAverageDelay");
    } 

    
    /**
     * Init all UI elements
     */
    public void initUI(){
        setContentView(R.layout.main);
        Log.d(getLogTag(), "initUI");

        addCigaretteButton 		= (Button) findViewById(R.id.home_add_cigarette_button);
        addPastCigaretteButton = (Button) findViewById(R.id.home_add_past_cigarette_button);
        showWeeklyStatButton 	= (Button) findViewById(R.id.home_button_history_week); 
        showMonthlyStatButton 	= (Button) findViewById(R.id.home_button_history_month);
        
        dailyCountValue = (TextView) findViewById(R.id.home_daily_count_value_field);
        //delayValue 		= (TextView) findViewById(R.id.home_average_delay_value_field);
        lastCigValue 	= (TextView) findViewById(R.id.home_delay_last_value_field);
        avgWeekValue	= (TextView) findViewById(R.id.home_week_average_value_field);
        avgMonthValue	= (TextView) findViewById(R.id.home_month_average_value_field);
        
        cigarette 	= getResources().getString(R.string.cigarette);
        day 	  	= getResources().getString(R.string.day);
        days 	  	= getResources().getString(R.string.days);
        hour 		= getResources().getString(R.string.hour);
        minute 	  	= getResources().getString(R.string.minute);
        minutes	  	= getResources().getString(R.string.minutes);
    }    
    
    /**
     * Method used to update the UI after called to initValues()
     */
    public void updateUI(){
    	Log.d(getLogTag(), "updateUI");
    	
    	showDailyCount();
    	
    	showDelaySinceLast();
    	
    	showAverageDelay();
    	
    	showWeeklyAverage();
    	
    	showMonthlyAverage();
    
    }
    
    /**
     * Method used to show/refresh all values on Main View
     */
    public void retieveDataFromDB(){
    	Log.d(getLogTag(), "retrieveDataFromDB");
    	
    	dailyCount = db.getDailyAdapter().getDailyCount();
    	
    	weekAvg = db.getWeeklyAdapter().getAverage();
    	
    	monthAvg = db.getMonthlyAdapter().getAverage();
    	
    	last = db.getDailyAdapter().getDelaySinceLast();
    	
    	//delay = db.getAverageDelay();
    }
        
    /**
     * Method called when a click is made on the "+1 button"
     */
    public void clickAddButton(){
    	Log.d(getLogTag(), "Click on Add Button");

    	/* Insert current TimeStamp */
    	db.insertCurrentTimestamp("", cigarettePrice);

    	/* Retrieve data from DB */
    	retieveDataFromDB();

    	/* Update UI values */
    	updateUI();

    	pref.setDailyCount(dailyCount);
    	
    	// Update widget(s)
    	CigaretteCounterWidger.updateAllWidgets(this.getApplicationContext());

    	/* Display a quick message */
    	Toast.makeText(this, R.string.home_insert_OK, Toast.LENGTH_SHORT).show();
    }
    
    /**
     * Method called when a click is made on the "Add Past Cigarette" button
     */
    public void clickAddPastButton(){
    	Log.d(getLogTag(), "Click on Add Past Button");

    	/* Init Dialog box */
    	final AlertDialog dialog = new AlertDialog.Builder(this).create();
    	dialog.show();
    	dialog.setContentView(R.layout.datetime_dialog);

    	/* Init Components */
    	final Button addPastButton 	= (Button) 		dialog.findViewById(R.id.dialog_add_button);
    	final Button cancelButton 	= (Button) 		dialog.findViewById(R.id.dialog_cancel_button);
    	final DatePicker datePicker = (DatePicker) 	dialog.findViewById(R.id.dialog_datePicker);
    	final TimePicker timePicker = (TimePicker) 	dialog.findViewById(R.id.dialog_timePicker);
    	timePicker.setIs24HourView(true);

    	final Spinner boxSpinner 	= (Spinner) 	dialog.findViewById(R.id.dialog_nb_cigarette);
    	final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( CigaretteCounter.this, R.array.cigarettes_array, android.R.layout.simple_spinner_item);

    	/* Define ListBox Values */
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		boxSpinner.setAdapter(adapter);
		boxSpinner.setSelection(0);

    	/* Retrieve number of cigarettes selected */
		boxSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { 
				try {
					String res = parent.getItemAtPosition(pos).toString(); 
					nbCigarettes = Integer.valueOf(res.substring(1, 2));
				} catch (NumberFormatException e) {
					nbCigarettes = 1;
				}
			} 

			public void onNothingSelected(AdapterView<?> parent) { } 
		});

    	/* Click Handler for Valid Button */
    	addPastButton.setOnClickListener(new OnClickListener() {              
    		public void onClick(View v) {
    			showWaitingMessage();
    			Log.d(getLogTag(), "Click Monthly Stats Button");                  

    			/* Retrieve Date & Time from Pickers */
    			int hour = timePicker.getCurrentHour();
    			int minute = timePicker.getCurrentMinute();

    			int day = datePicker.getDayOfMonth();
    			int month = datePicker.getMonth();
    			int year = datePicker.getYear();

    			Calendar c = Calendar.getInstance();
    			c.setTimeZone(TimeZone.getDefault());
    			c.set(Calendar.YEAR, year);
    			c.set(Calendar.MONTH, month);
    			c.set(Calendar.DAY_OF_MONTH, day);

    			c.set(Calendar.HOUR_OF_DAY, hour);
    			c.set(Calendar.MINUTE, minute);
    			c.set(Calendar.SECOND, 0);
    			c.set(Calendar.MILLISECOND, 0);

				long timestamp = c.getTimeInMillis()/1000;

    			/* Insert current TimeStamp */
    			for ( int i = 0 ; i < nbCigarettes ; i++ )
    				db.insertTimestamp(cigarettePrice, timestamp, "Past Data");

    			/* Retrieve data from DB */
    			retieveDataFromDB();

    			/* Update UI values */
    			updateUI();

    	    	pref.setDailyCount(dailyCount);

    	    	// Update widget(s)
    	    	CigaretteCounterWidger.updateAllWidgets(CigaretteCounter.this.getApplicationContext());

    			/* Display a quick message */
    			dialog.dismiss();
    			hideWaitingMessage(getResources().getString(R.string.home_insert_X_OK, nbCigarettes+""));
    		}          
    	});  

    	/* Click Handler for Cancel Button */
    	cancelButton.setOnClickListener(new OnClickListener() {              
    		public void onClick(View v) {
    			dialog.dismiss();
    		}
    	});
    }

	/**
	 * Method used to defined all UI handlers
	 */
    public void initHandlers(){
    	Log.d(getLogTag(), "initHandlers");
        // Listeners & Handlers 
        addCigaretteButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	Log.d(getLogTag(), "Click Add Button");
            	clickAddButton();
            }
        });
        
        addPastCigaretteButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	Log.d(getLogTag(), "Click Add Past Button");
              clickAddPastButton();
            }
        });
        
        showWeeklyStatButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	Log.d(getLogTag(), "Click Weekly Stats Button");
            	showView(VIEW.WEEKLY);
            }
        });
        
        showMonthlyStatButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	Log.d(getLogTag(), "Click Monthly Stats Button");
            	showView(VIEW.MONTHLY);
            }
        });
    }

}
